import toolkit from './toolkit.js';
export default {
	generate(){
		while(!this.internalGenerate()){
			console.log('重新尝试')
		}
		return this.matrix;
		
	},
	internalGenerate(){
		this.matrix  = toolkit.makeMatrix();
		this.count = 0;
		this.orders = toolkit.makeMatrix()
		.map(row => row.map((v,i)=> i))
		.map(row => toolkit.shuffle(row))
		for(let n=1;n<10;n++){
			if(!this.fillNumber(n)){
				return false;
			}			
		}
		return true ;
	},
	fillNumber(n){
		return this.fillRow(n,0)		
	},
	fillRow(n,rowIndex){
		if(rowIndex>8){
			return true;
		}
		const row = this.matrix[rowIndex];
		const orders = this.orders[rowIndex];
		for(let i=0;i<9;i++){
			this.count++
			const colIndex = orders[i];
			if(row[colIndex]){
				continue;
			}
			//检查当前位置是否可填
			if(!toolkit.checkFillable(this.matrix,n,rowIndex,colIndex)){
				continue;
			}
			
			row[colIndex] = n;
//			console.log(row)
			//当前行填写n成功，递归
			if(!this.fillRow(n,rowIndex+1)){
				row[colIndex] = 0;
				continue;
			}
			return true;
			
		}	
		return false;
	}
}

